package com.ycsj.goldmedalnewconcept.conversationphoto;

import io.rong.photoview.PhotoView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nineoldandroids.animation.Animator;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.constant.MyApplication;

/**
 * 网络头像大图展示
 * 
 * @author 
 * 
 */
public class BigPicShowActivity extends Activity implements OnPageChangeListener {

	private Animator mCurrentAnimator;
	private int mShortAnimationDuration = 300;
	private LayoutInflater inflater;
	private Map<String, Bitmap> listbit;
	private List<String> urllist=new ArrayList<String>();
	// 是否是第一次显示，判断是否弹出窗口
	private boolean isFirstShow = true;
	float startScale;
	HackyViewPager viewPager;
	Rect startBounds;
	float startScaleFinal;
	private AsyncImageTask ait;
	private SamplePagerAdapter adapter;

	private View mParentView;
	private TextView tb_title;
	private ImageButton tb_back;
	private RelativeLayout tb_rl;
	private Button titlebar_save;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showbigpicview);
		initView();
		tb_back.setVisibility(tb_back.VISIBLE);
		titlebar_save.setVisibility(titlebar_save.GONE);
	}

	private void initView() {
		if (MyApplication.getShowPicMap() != null) {
			listbit = MyApplication.getShowPicMap();
		} else {
			listbit = new HashMap<String, Bitmap>();
		}
		int position = getIntent().getIntExtra("position", 0);
		urllist = getIntent().getStringArrayListExtra("urllist");
		if(urllist==null||urllist.size()==0){
			
			
			finish();
			Toast.makeText(BigPicShowActivity.this, "该用户头像暂时无法显示", 0).show();
			return;
		}
		mParentView = View.inflate(this, R.layout.showbigpicview, null);
		viewPager = (HackyViewPager) findViewById(R.id.expanded_image);
		tb_rl = (RelativeLayout) findViewById(R.id.titlebar_rl);
		tb_back = (ImageButton) findViewById(R.id.titlebar_back_ib);
		tb_title = (TextView) findViewById(R.id.titlebar_title_tv);

		 bar = (ProgressBar) findViewById(R.id.bar); 
		
		 titlebar_save = (Button) findViewById(R.id.titlebar_save);
		 titlebar_save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				String string = urllist.get(22);
				
				down();  
			}
		});
		
		tb_back.setVisibility(View.VISIBLE);
		tb_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		if(urllist!=null&&urllist.size()==0){
			getPicList(position);
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		MyApplication.showpicmap = listbit;
	}

	/**
	 * 	获取图片和展示
	 * 
	 * @param listview
	 * @param listurl
	 * @param position
	 */
	public void getPicList(int position) {
//		tb_title.setVisibility(View.VISIBLE);
		
		if (listbit.keySet().contains(urllist.get(position))) {
			if (isFirstShow) {
				zoomImageFromThumb(position);
			} else {
				adapter = new SamplePagerAdapter(position);
				viewPager.setAdapter(adapter);
				viewPager.setCurrentItem(position);
			}
		} else {
			
			if (urllist.get(position).startsWith("http")) {
				if (ait == null) {
					ait = new AsyncImageTask(urllist.get(position), position);
					ait.execute();
				}
			} else {
				showLocalPic(urllist.get(position), position);
			}
		}

	}

	/**
	 * 展示本地图片
	 * 
	 * @param view
	 * @param path
	 * @param position
	 */
	private void showLocalPic(String path, int position) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		listbit.put(path, bitmap);
		if (isFirstShow) {
			zoomImageFromThumb(position);
		} else {
			adapter = new SamplePagerAdapter(position);
			viewPager.setAdapter(adapter);
			viewPager.setCurrentItem(position);
		}
	}

	// 异步获取图片
	private final class AsyncImageTask extends AsyncTask<Void, Void, Void> {
		private String url;
		private int Position;

		private AsyncImageTask(String imageUrl, int position) {
			url = imageUrl;
			Position = position;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			InputStream inputStream;
			try {
				inputStream = new URL(url).openStream();
				Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
				listbit.put(url, bitmap);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			ProgressDialogUtils.dissProgressdialog();
			if (isFirstShow) {
				zoomImageFromThumb(Position);
			} else {
				adapter = new SamplePagerAdapter(Position);
				viewPager.setAdapter(adapter);
				viewPager.setCurrentItem(Position);
			}
			ait = null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			ProgressDialogUtils.showProgressdialog(BigPicShowActivity.this,
					"加载中...");
		}

	}

	private void zoomImageFromThumb(int position) {
		// If there's an animation in progress, cancel it immediately and
		// proceed with this one.
		if (mCurrentAnimator != null) {
			mCurrentAnimator.cancel();
		}

		adapter = new SamplePagerAdapter(position);
		viewPager.setAdapter(adapter);
		viewPager.setCurrentItem(position);
		viewPager.setOnPageChangeListener(this);

	}

	class SamplePagerAdapter extends PagerAdapter {

		private int mPosition;

		public SamplePagerAdapter(int position) {
			this.mPosition = position;
		}

		@Override
		public int getCount() {
			return urllist.size();
		}

		@Override
		public View instantiateItem(ViewGroup container, final int position) {
			final PhotoView photoView = new PhotoView(container.getContext());
			if (listbit.keySet().contains(urllist.get(position))) {
				photoView.setImageBitmap(listbit.get(urllist.get(position)));
			}

			// Now just add PhotoView to ViewPager and return it
			container.addView(photoView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);
			photoView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					finish();
				}
			});
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}

	/**
	 * 清除对象
	 */
	public void clearMap() {
		listbit.clear();
		listbit = null;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		isFirstShow = false;
		tb_title.setText(position + 1 + "/" + urllist.size());
		if (!(listbit.keySet()).contains(urllist.get(position))) {
			getPicList(position);
			
		}
	}
	
	
	OutputStream output;// 输入出流  
	ProgressBar bar; 
	
	// 下载方法 必须放在单独的线程里  
    private void down() throws RuntimeException {  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                try {  
                    Message m = handler.obtainMessage();  
                    
                    m.what = 0;  
                    m.sendToTarget();  
                    // 创建URL 写入下载地址   17190185038
                    URL url = new URL( urllist.get(0)); 
                    Log.e("home", urllist.get(0));
                    String[] split = urllist.get(0).split("/");
                    Log.e("home", split[split.length-1]);
                    // 创建HttpURLConnection  
                    HttpURLConnection urlcon = (HttpURLConnection) url  
                            .openConnection();  
                    //或者上两句使用URLConnection connection = new URL("下载路径").  
                    //openConnection(); 下面的urlcon 换成connection   
                    // 获得文件大小  
                    long TotalSize = Long.parseLong(urlcon  
                            .getHeaderField("Content-Length"));  
                    // 获得文件大小  
                    int fileLength = urlcon.getContentLength();  
                    // 获得输入流  
                    InputStream is = urlcon.getInputStream();  
                    // 创建目录  
                    File dir = new File("/mnt/sdcard/jinpaijun");  
                    dir.mkdir();  
                    // 创建文件  
                    File file = new File("/mnt/sdcard/jinpaijun/"+split[split.length-1]);  
                    // 如果存在则删除  
                    if(file.exists())  
                        file.delete();  
                    // 创建文件  
                    file.createNewFile();  
                    // 创建文件输入流  
                    output = new FileOutputStream(file);  
                    byte buffer[] = new byte[4 * 1024];  
                    // 已下载  
                    int downsize = 0;  
  
                    while(true) {  
                        int down = is.read(buffer);  
                        if(down == -1) {  
                            break;  
                        }  
                        downsize += down;  
                        output.write(buffer, 0, down);  
                        Message m2 = handler.obtainMessage();  
                        m2.what = 1;  
                        // 提示已下载百分之多少  
                        m2.arg1 = downsize * 100 / fileLength;  
                        m2.sendToTarget();  
                    }  
                    // 清除缓存  
                    output.flush();  
                }  
                catch(Exception e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
                finally {  
                    try {  
                        // 关闭输出流  
                        output.close();  
                       
                    }  
                    catch(Exception e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }).start();  
    } 
    
    
    Handler handler = new Handler() {  
    	  
        @Override  
        public void handleMessage(Message msg) {  
            // TODO Auto-generated method stub  
            super.handleMessage(msg);  
            switch(msg.what) {  
                case 0:  
                    bar.setVisibility(View.VISIBLE);  
                    break;  
                case 1:  
                    bar.setProgress(msg.arg1);
                    if(msg.arg1==100){
                    	 Toast.makeText(BigPicShowActivity.this, "保存成功！", 0).show();
                    }
                    break;  
            }  
        }  
    };  

}